let app = getApp()
const db = wx.cloud.database({env: app.globalData.CLOUD_ENV})
const DBClassify = db.collection('db_classifys')
const DBInterview = db.collection('db_topic')
let d = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    classifys:[],
    array: [],
    columns: [
      'h5', 
      'java', 
      '嵌入式', 
      'php', 
      'python'
    ],
    num: 0,
    type: 'h5',
    index: 0,
    q: '',
    q2:'',
    a: '',
    a2: '',
    text: '',
    id:''
  },
  bindPickerChange2(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let num = e.detail.value;
    let type = this.data.columns[num];
    if(this.data.classifys.length ==0) return;
    let arr = this.data.classifys.filter(item => {
        // if(item.type == type){
          return item.type == type
        // }
    })
    let newArr = arr.map(item=> item.text)
    // console.log('xx-',arr)
    // console.log('xx-',type)
    this.setData({
      num: num,
      type: type,
      array: newArr 
    })
  },
   // 分类列表
   async listClassifyFn() {
    let res = await DBClassify.where({}).count()
    let count = res.total;
    let all = [];
    for(let i = 0 ; i < count ; i+= 20){
        await DBClassify.where({}).skip(i).get()
        .then(
          content => {
            // console.log('3.0', content)
            let {data} = content;
            if(data.length!=0){
              all = all.concat(data)
            }
          }
        )
    }

    let type = this.data.type
    let arr = all.map(item => {
        if(item.type == type){
          return item.text
        }
    })
    this.setData({
      classifys: all,
      array: arr
    })
  },

  copyText(e) {
    let key = e.currentTarget.dataset.key;
    // console.log('--',key)
    wx.setClipboardData({ //设置系统剪贴板的内容
      data: key,
      success(res) {
        console.log(res, key);
        wx.getClipboardData({ // 获取系统剪贴板的内容
          success(res) {
            wx.showToast({
              title: '复制成功',
              icon: 'none'
            })
          }
        })
      },
      fail(err){
        console.log('11',err)
      }
    })
  },
  // 分类列表
  async listClassifyFnxx() {
    let that = this;
    await DBClassify.get()
      .then(
        content => {
          // console.log('3.0', content)
          if (content.data.length == 0) return
          let arr = content.data.map(item => item.text)
          // console.log('1:',arr)
          if (content.data) {
            that.setData({
              array: arr,
              text: arr[0]
            })
          }
        }
      )
  },
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      text: this.data.array[e.detail.value]
    })
  },
  addInputQ(e) {
    let text = e.detail.text;
    this.setData({
      q: text
    })
  },
  addInputA(e) {
    let text = e.detail.text;
    this.setData({
      a: text
    })
  },
  setA(text){
    let that = this
    //content是从数据库获取的数据里的delta字符串，然后装换为json
    // let option = {"delta":text};
    let content = JSON.stringify({delta: text})
    let query = wx.createSelectorQuery();//创建节点查询器 
    query.in(that).select('#editor2').context(function (res) {
      res.context.setContents({
        delta: JSON.parse(content),
        success: function (res) {
          // console.log(res.data)
        },
        fail: function (error) {
          console.log(error)
        }
      })
    }).exec()
  },
  setQ(text){
    let that = this
    //content是从数据库获取的数据里的delta字符串，然后装换为json
    let content = JSON.stringify({delta: text})
    console.log(content)
    let query = wx.createSelectorQuery();//创建节点查询器 
    query.in(that).select('#editor1').context(function (res) {
      res.context.setContents({
        delta: JSON.parse(content),
        success: function (res) {
          console.log(res)
        },
        fail: function (error) {
          console.log(error)
        }
      })
    }).exec()
  },
  // 点击提交
  addTopicFn(e) {
    let a = this.data.a;
    let q = this.data.q;
    let text = this.data.text;
    let type = this.data.type;
    if(a == '' || q == '') {
      wx.showToast({
        title: '输入框不能为空。',
        icon: 'none'
      })
      return;
    }
    // console.log({a,q,text})
    let create_time = new Date()
    let openid = wx.getStorageSync('openid')
    let _id = e.currentTarget.dataset.id || this.data.id;
    console.log({_id})
    if(_id == '') return;
    let option = {
      a,
      q,
      text
    };
    let that = this;
    if (openid) {
      if (d != null) return;
      d = setTimeout(async () => {
        // 检测敏感词
        wx.cloud.callFunction({
          name: 'msgsec',
          data: {
            content: JSON.stringify(option),
            openid
          },
          success(res) {
            let {
              result: {
                errCode,
                errMsg
              }
            } = res;
            console.log('检测结果:',res);//  errCode == 0 表示文本正常
            if (errCode == 0) {
              // 添加题目
              DBInterview.where({_id}).update({
                  data: {
                    openid,
                    a,
                    q,
                    text,
                    type,
                    create_time
                  }
                })
                .then(
                  content => {
                    // console.log('--->', content)
                    d=null;
                    let {
                      errMsg
                    } = content;
                    if (errMsg == "collection.update:ok") {
                      wx.showToast({
                        title: '修改成功。',
                        icon: 'none'
                      })
                      let delay = setTimeout(() => {
                        
                        // wx.navigateTo({
                        //   url: '../list/list',
                        // })
                        wx.redirectTo({
                          url: '../list/list',
                        })
                        clearTimeout(delay)
                        delay = null;
                      }, 300)
                    } else {
                      wx.showToast({
                        title: '修改失败。',
                        icon: 'none'
                      })
                    }
                  }
                )
            } else {
              if (errMsg != "openapi.security.msgSecCheck:ok") {
                wx.showToast({
                  title: '您输入的内容包含敏感词哦。',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: `${errMsg},${errCode}`,
                  icon: 'none'
                })
              }
            }
          }
        })
      }, 300)
    } else {
      wx.navigateTo({
        url: '../../../user/login/login',
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
   if(options) {
      await this.listClassifyFn()
      let {id} = options
      let that = this;
      if(id){
      await DBInterview.where({_id: id}).get().then(
          content=>{
            // console.log('1.0',content.data)
            let {errMsg,data} = content;
            if(errMsg == "collection.get:ok") {
              let index = 0;
              let  num = 0;
              let text = content.data[0].text;
              let type = content.data[0].type;
              this.data.columns.forEach((item,i)=>{
                if(item == type) {
                  num = i
                }
              })
              this.data.array.forEach((item,i)=>{
                  if(text==item){
                    index = i;
                  }
              })
              // console.log(data,value,text)
              that.setData({
                q2: data[0].q,
                a2: data[0].a,
                id,
                text: this.data.array[index],
                type: this.data.columns[num],
                index,
                num
              })
              that.setA(data[0].a)
              that.setQ(data[0].q)
            }
          }
        )
      }
   }
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})